package org.KeyCrafter.obj.type;

import org.KeyCrafter.ds.list.LinkedList;
import org.KeyCrafter.ds.list.List;
import org.KeyCrafter.ds.list.ListIter;

import java.util.Iterator;

public class DefaultListType implements ListType{
    private List list  = new LinkedList();
    @Override
    public byte encoding() {
        return KeyCrafter_ENCODING_LINKEDLIST;
    }

    @Override
    public Object content() {
        return this.list;
    }

    @Override
    public Object pop(int whrere) {
        List.Node ln;
        if (whrere == KeyCrafter_HEAD) {
            ln = list.first();
        } else {
            ln = list.last();
        }
        // 删除被弹出的节点
        if (ln != null){
            list.delNode(ln);
            return ln.getValue();
        } else {
            return null;
        }
    }

    @Override
    public void push(Object value, int where) {
        if (where == KeyCrafter_HEAD){
            this.list.addNodeHead(value);
        } else {
            this.list.addNodeTail(value);
        }
    }

    @Override
    public Iterator iterator() {
        ListIter iterator = list.getIterator();
        return new Iterator() {
            @Override
            public boolean hasNext() {
                return iterator.hasNext();
            }

            @Override
            public Object next() {
                return iterator.next().getValue();
            }
        };
    }

    @Override
    public void range(long start, long len, String[] reply) {
        if (reply.length < len){
            throw new IndexOutOfBoundsException("The array length needs to be greater than " + len);
        }
        if (start > len / 2) {
            start -= len;
        }
        List.Node ln = list.index(start);
        for (int i = 0; i < len; i++){
            reply[i] = ln.getValue().toString();
            ln = ln.getNext();
        }
    }

    @Override
    public long length() {
        return this.list.length();
    }
}
